# Block reform: "Industries that block beneficial reforms do not deserve compensation from taxpayer dollars."
# Harm society: "Industries that harm society do not deserve compensation from taxpayer dollars."
# Moral hazrd: "Compensating one industry will encourage other industries to block beneficial reforms in the future."
# Government interference: "By making large payments to industries, the government is interfering too much with the economy."
# Industry deserves protection: "This industry, and the jobs it represents, deserve government protection."
# "Other"

source(here::here("code/load.R"))

dict <- c(
    "approval_coal_4" = "coal",
    "vignette_coal_1" = "coal_buyout",
    "reneging_coal_1" = "coal_renege",
    "approval_tax_4" = "tax",
    "vignette_tax_1" = "tax_buyout",
    "reneging_tax_1" = "tax_renege")

cr <- c(
    "(Intercept)" = "(Intercept)",
    "coal" = "Baseline",
    "tax" = "Baseline",
    "taxbinStrong opposition" = "Strong opposition",
    "taxbinWeak opposition" = "Weak opposition",
    "taxbinNeutral" = "Neutral",
    "taxbinStrong support" = "Strong support",
    "taxbinWeak support" = "Weak support",
    "coalbin" = "Baseline",
    "coalbinStrong opposition" = "Strong opposition",
    "coalbinWeak opposition" = "Weak opposition",
    "coalbinNeutral" = "Neutral",
    "coalbinStrong support" = "Strong support",
    "coalbinWeak support" = "Weak support",
    "coal_buyout" = "Buyout support",
    "tax_buyout" = "Buyout support",
    "moral_c" = "Consequentialist",
    "moral_d" = "Deontological",
    "partyIndependent" = "Independent",
    "partyRepublican" = "Republican",
    "partyDemocrat" = "Democrat",
    "education_censusLess than high school graduate" = "Less than high school",
    "education_censusHigh school graduate" = "High school",
    "education_censusSome college or associate's degree" = "Some college",
    "education_censusSome college or associate s degree" = "Some college",
    "education_censusUniversity completed or higher" = "University completed or higher",
    "age_census35-54" = "35-54", 
    "age_census55+" = "55+", 
    "genderWoman" = "Woman"
    )


dat <- readRDS(here("data/data_2022-08.rds"))
dat[, `:=` (
    moral_d = rowMeans(dat[, .SD, .SDcols = patterns("^moral\\_.*[1|2|3|4]$")], na.rm = TRUE),
    moral_c = rowMeans(dat[, .SD, .SDcols = patterns("^moral\\_.*[5|6|7|8]$")], na.rm = TRUE))]
setnames(dat, old = names(dict), new = dict)
setnames(dat, gsub("counter_coal", "coal_counter", colnames(dat)))
setnames(dat, gsub("counter_tax", "tax_counter", colnames(dat)))

tmp <- dat[, .SD, .SDcols = patterns("^respondent$|^party|^coal|^tax|^moral_[d|c]$|wts|education_census|age_census|gender")]

mod <- list(
    "I" = lm(coal_buyout ~ moral_d + coal, data = tmp),
    "II" = lm(coal_buyout ~ moral_c + coal, data = tmp),
    "III" = lm(tax_buyout ~ moral_d + tax, data = tmp),
    "IV" = lm(tax_buyout ~ moral_c + tax, data = tmp))

modelsummary(
    mod,
    escape = FALSE,
    title = "Determinants of support for buyout proposals.\\label{tab:support}",
    coef_map = cr,
    vcov = "HC3",
    output = "latex",
    gof_map = c("nobs", "r.squared", "vcov.type"))  |>
    group_tt(j = list("Coal" = 2:3, "Tax" = 4:5)) |>
    save_tt(here("txt/fig/buyout_moral_regression_baseline_control_2022-08.tex"), overwrite = TRUE)


mod <- list(
    "I" = lm(weights = wts, coal_buyout ~ moral_d + coal, data = tmp),
    "II" = lm(weights = wts, coal_buyout ~ moral_c + coal, data = tmp),
    "III" = lm(weights = wts, tax_buyout ~ moral_d + tax, data = tmp),
    "IV" = lm(weights = wts, tax_buyout ~ moral_c + tax, data = tmp))

modelsummary(
    mod,
    escape = FALSE,
    title = "Determinants of support for buyout proposals, using survey weights.\\label{tab:supportwts}",
    coef_map = cr,
    gof_map = c("nobs", "r.squared"),
    output = "latex",
    vcov = "HC3",
    gof_omit = "Std")  |>
    group_tt(j = list("Coal" = 2:3, "Tax" = 4:5)) |>
    save_tt(here("txt/fig/buyout_moral_regression_baseline_wts_2022-08.tex"), overwrite = TRUE)

mod <- list(
    "I" = lm(coal_renege ~ coal + coal_buyout + moral_d, data = tmp),
    "II" = lm(coal_renege ~ coal + coal_buyout + moral_c, data = tmp),
    "III" = lm(tax_renege ~ tax + tax_buyout + moral_d, data = tmp),
    "IV" = lm(tax_renege ~ tax + tax_buyout + moral_c, data = tmp))
modelsummary(mod)

mod <- list(
    "I" = lm(coal_renege ~ coal + moral_d, data = tmp),
    "II" = lm(coal_renege ~ coal + moral_c, data = tmp),
    "III" = lm(tax_renege ~ tax + moral_d, data = tmp),
    "IV" = lm(tax_renege ~ tax + moral_c, data = tmp))
modelsummary(
    mod,
    escape = FALSE,
    title = "Determinants of support for reneging on a buyout promise\\label{tab:renege}",
    coef_map = cr,
    vcov = "HC3",
    gof_map = c("nobs", "r.squared", "vcov.type"),
    output = "latex")  |>
    group_tt(j = list("Coal" = 2:3, "Tax" = 4:5)) |>
    save_tt(here("txt/fig/renege_regression_2022-08.tex"), overwrite = TRUE)

mod <- list(
    "I" = lm(weights = wts, coal_renege ~ coal + moral_d, data = tmp),
    "II" = lm(weights = wts, coal_renege ~ coal + moral_c, data = tmp),
    "III" = lm(weights = wts, tax_renege ~ tax + moral_d, data = tmp),
    "IV" = lm(weights = wts, tax_renege ~ tax + moral_c, data = tmp))
modelsummary(
    mod,
    escape = FALSE,
    title = "Determinants of support for reneging on a buyout promise, using survey weights.\\label{tab:renegewts}",
    coef_map = cr,
    vcov = "HC3",
    gof_map = c("nobs", "r.squared", "vcov.type"),
    output = "latex")  |>
    group_tt(j = list("Coal" = 2:3, "Tax" = 4:5)) |>
    save_tt(here("txt/fig/renege_regression_baseline_wts_2022-08.tex"), overwrite = TRUE)

## ----echo = FALSE, fig.cap = "Support for coal buyouts, by level of baseline support and moral dimension."----
datplot <- tmp[, .SD, .SDcols = c("moral_c", "moral_d", "coal", "coal_buyout")]
datplot <- datplot[, lapply(.SD, round)]
datplot <- melt(datplot, id.vars = c("coal", "coal_buyout"), value.name = "moral", "variable.name" = "Moral dimension")
datplot[, `Moral dimension` := ifelse(`Moral dimension` == "moral_c", "Consequentialist", "Deontological")]
datplot <- datplot[, .(buyout = mean(coal_buyout)), by = c("coal", "Moral dimension", "moral")]
p <- ggplot(datplot, aes(moral, coal, fill = buyout)) +
    geom_tile() +
    coord_fixed() +
    labs(x = "",
         y = "Support coal shutdown",
         fill = "Support coal buyout") +
    scale_fill_continuous(trans = "reverse") +
    facet_wrap(~ `Moral dimension`)
ggsave(p,
    filename = here("txt/fig/coal_buyout_moral_2022-08.pdf"),
    width = 6, height = 2.5)


## ----echo = FALSE, fig.cap = "Support for tax buyouts, by level of baseline support and moral dimension."----
datplot <- tmp[, .SD, .SDcols = c("moral_c", "moral_d", "tax", "tax_buyout")]
datplot <- datplot[, lapply(.SD, round)]
datplot <- melt(datplot, id.vars = c("tax", "tax_buyout"), value.name = "moral", "variable.name" = "Moral dimension")
datplot[, `Moral dimension` := ifelse(`Moral dimension` == "moral_c", "Consequentialist", "Deontological")]
datplot <- datplot[, .(buyout = mean(tax_buyout)), by = c("tax", "Moral dimension", "moral")]
p <- ggplot(datplot, aes(moral, tax, fill = buyout)) +
    geom_tile() +
    coord_fixed() +
    labs(x = "",
         y = "Support tax simplification",
         fill = "Support tax buyout") +
    scale_fill_continuous(trans = "reverse") +
    facet_wrap(~ `Moral dimension`)
ggsave(p,
    filename = here("txt/fig/tax_buyout_moral_2022-08.pdf"),
    width = 6, height = 2.5)


## ----echo = FALSE, warning = FALSE, message = FALSE, fig.asp = .4, fig.cap = "Please rank the best reasons to oppose a coal industry buyout."----
counter_dict <- c(
    "1" = "Block reform",
    "2" = "Harm society",
    "3" = "Moral hazard",
    "4" = "Government interference",
    "5" = "Industry deserves",
    "6" = "Other")
counter <- tmp[, .SD, .SDcols = patterns("^respondent$|coal_counter_\\d$")]
counter <- melt(counter, id.vars = "respondent", variable.name = "argument", value.name = "rank")
counter[, argument := gsub(".*_", "", argument)]
counter[, argument := counter_dict[match(argument, names(counter_dict))]]
counter <- counter[, as.list(prop.table(table(rank)) * 100), by = "argument"]
counter <- melt(counter, id.vars = "argument", variable.name = "Rank", value.name = "pct")
l <- counter[Rank == "1"][order(pct)]$argument
counter[, argument := factor(argument, levels = l)]
counter[, Rank := factor(Rank, levels = as.character(6:1))]
p <- ggplot(counter, aes(pct, argument, fill = Rank)) +
    geom_bar(position = 'stack', stat = 'identity') +
    labs(y = "", x = "% of Respondents") +
    theme_minimal() +
    theme(text = element_text(family = "serif"),
          panel.grid = element_blank(),
          legend.position = "right") +
    scale_fill_okabe_ito() +
    scale_y_discrete() +
    guides(fill = guide_legend(reverse = TRUE)) 
ggsave(p,
    filename = here("txt/fig/coal_reasons_2022-08.pdf"),
    width = 6, height = 1.5)


## ----echo = FALSE, warning = FALSE, message = FALSE, fig.asp = .4, fig.cap = "Please rank the best reasons to oppose a tax industry buyout."----
counter_dict <- c(
    "1" = "Block reform",
    "2" = "Harm society",
    "3" = "Moral hazard",
    "4" = "Government interference",
    "5" = "Industry deserves",
    "6" = "Other")
counter <- tmp[, .SD, .SDcols = patterns("^respondent$|tax_counter_\\d$")]
counter <- melt(counter, id.vars = "respondent", variable.name = "argument", value.name = "rank")
counter[, argument := gsub(".*_", "", argument)]
counter[, argument := counter_dict[match(argument, names(counter_dict))]]
counter <- counter[, as.list(prop.table(table(rank)) * 100), by = "argument"]
counter <- melt(counter, id.vars = "argument", variable.name = "Rank", value.name = "pct")
l <- counter[Rank == "1"][order(pct)]$argument
counter[, argument := factor(argument, levels = l)]
counter[, Rank := factor(Rank, levels = as.character(6:1))]
p <- ggplot(counter, aes(pct, argument, fill = Rank)) +
    geom_bar(position = 'stack', stat = 'identity') +
    labs(y = "", x = "% of Respondents") +
    theme_minimal() +
    theme(text = element_text(family = "serif"),
          panel.grid = element_blank(),
          legend.position = "right") +
    scale_fill_okabe_ito() +
    scale_y_discrete() +
    guides(fill = guide_legend(reverse = TRUE)) 
ggsave(p,
    filename = here("txt/fig/tax_reasons_2022-08.pdf"),
    width = 6, height = 1.5)



# Old Table 9 for Reviewer 4
mod <- list(
    "I" = lm(coal_buyout ~ moral_d + coal + age_census + gender + education_census + party, data = tmp),
    "II" = lm(coal_buyout ~ moral_c + coal + age_census + gender + education_census + party, data = tmp),
    "III" = lm(tax_buyout ~ moral_d + tax + age_census + gender + education_census + party, data = tmp),
    "IV" = lm(tax_buyout ~ moral_c + tax + age_census + gender + education_census + party, data = tmp))

modelsummary(
    mod,
    escape = FALSE,
    title = "Determinants of support for buyout proposals, controling for baseline level of support, age, gender, education, and party id.\\label{tab:supportsocio}",
    coef_map = cr,
    vcov = "HC3",
    output = "latex",
    gof_map = c("nobs", "r.squared", "vcov.type"))  |>
    group_tt(j = list("Coal" = 2:3, "Tax" = 4:5)) |>
    save_tt(here("txt/fig/buyout_moral_regression_baseline_socio_2022-08.tex"), overwrite = TRUE)




## ----echo = FALSE, warning = FALSE, message = FALSE---------------------------
datasummary(
    escape = FALSE,
    (`Coal shutdown` = coal) + (`Tax simplification` = tax) ~ party * (Mean + SD) + Mean + SD,
    title = "Republicans are less likely to support coal shutdown than Democrats. Democrats and Republicans support tax simplification in about equal measure.\\label{tab:partyissuecrosstab}",
    output = here("txt/fig/party_issue_crosstab_2022-08.tex"),
    data = tmp)


tmp[, coalbin := fcase(
        coal < 2.5, "Strong opposition",
        coal >= 2.5 & coal < 5, "Weak opposition",
        coal == 5, "Neutral",
        coal >= 5 & coal < 7.5, "Weak support",
        coal >= 7.5, "Strong support")][
    , taxbin := fcase(
        tax < 2.5, "Strong opposition",
        tax >= 2.5 & tax < 5, "Weak opposition",
        tax == 5, "Neutral",
        tax >= 5 & tax < 7.5, "Weak support",
        tax >= 7.5, "Strong support")][
    , taxbin := factor(taxbin, levels = c("Strong opposition", "Weak opposition", "Neutral", "Weak support", "Strong support"))][
    , coalbin := factor(coalbin, levels = c("Strong opposition", "Weak opposition", "Neutral", "Weak support", "Strong support"))]

mod <- list(
    lm(coal_renege ~ moral_d * coalbin + moral_c * coalbin, data = tmp),
    lm(tax_renege ~ moral_d * taxbin + moral_c * taxbin, data = tmp)
)

mfx <- mod
mfx[[1]] <- avg_predictions(mod[[1]], by = "coalbin") |> transform(Issue = "Coal")
mfx[[2]] <- avg_predictions(mod[[2]], by = "taxbin") |> transform(Issue = "Tax")
setnames(mfx[[1]], old = "coalbin", new = "Support")
setnames(mfx[[2]], old = "taxbin", new = "Support")
mfx <- rbindlist(mfx, fill = TRUE)

p <- ggplot(mfx, aes(x = estimate, xmin = conf.low, xmax = conf.high, y = Support)) +
    geom_pointrange() +
    facet_wrap(~ Issue) +
    xlab("Predicted level of support for reneging") +
    ylab("") +
    theme_bw() +
    theme(strip.background = element_blank())
ggsave(p, filename = here("txt/fig/reneging_polarization_2022-08.pdf"), width = 5, height = 2)
ggsave(p, filename = here("txt/fig/reneging_polarization_2022-08.jpg"), width = 5, height = 2)



# slope of moral_d and moral_c for each level of support
mfx <- list()
mfx[[1]] <- avg_slopes(mod[[1]], variables = c("moral_d", "moral_c"), by = "coalbin", vcov = "HC3")
mfx[[2]] <- avg_slopes(mod[[2]], variables = c("moral_d", "moral_c"), by = "taxbin", vcov = "HC3")
setnames(mfx[[1]], old = "coalbin", new = "Support")
setnames(mfx[[2]], old = "taxbin", new = "Support")
mfx[[1]]$Issue <- "Coal"
mfx[[2]]$Issue <- "Tax"
mfx <- rbindlist(mfx)
mfx$term <- ifelse(mfx$term == "moral_c", "Consequentialist", "Deontological")

p <- ggplot(mfx, aes(x = estimate, xmin = conf.low, xmax = conf.high, y = Support)) +
    geom_pointrange() +
    facet_grid(term ~ Issue) +
    xlab("Marginal effect of moral reasoning on support for reneging") +
    ylab("") +
    theme_bw() +
    theme(strip.background = element_blank())
ggsave(p, filename = here("txt/fig/reneging_moral_polarization_2022-08.pdf"), width = 7, height = 5)
ggsave(p, filename = here("txt/fig/reneging_moral_polarization_2022-08.jpg"), width = 7, height = 5)

